// components/search-courses/search-courses.js
import { getCourseCatigories, getCoursesList } from '../../api/courses'
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    focus: Boolean
  },

  /**
   * 组件的初始数据
   */
  data: {
    categoryId: -1,
    searchKeyword: '',
    categoriesList: [
      // {
      //   id: '-1',
      //   name: '全部'
      // }
    ],
    courseList: [
      // {
      //   id: '1',
      //   title: '课程名称1111',
      //   subject: '化学',
      //   price: '99',
      //   priceOld: 200,
      //   buyCount: 155,
      //   thumb: 'https://img30.360buyimg.com/babel/s590x470_jfs/t1/163664/11/237/172437/5fedc026E18f95c63/f173a578ad46d5cb.jpg.webp'
      // }
    ]
  },

  // onReady: function () {
  // },
  attached() {
    this.initCategoriesList()
    this.loadCourseList()
  },

  /**
   * 组件的方法列表
   */
  methods: {
    async initCategoriesList() {
      let list = await getCourseCatigories()
      this.setData({
        categoriesList: list.map(({ id, name }) => ({ id, name }))
      })
    },
    loadCourseList(page = 1) {
      let {categoryId, searchKeyword} = this.data
      return getCoursesList({
        page,
        keyword: searchKeyword || undefined,
        category_id: categoryId === -1 ? undefined : categoryId,
      }, { hasLoading: false }).then(data => {
        let list = data.data.map(item => {
          return {
            id: item.id,
            title: item.title,
            subject: '课程',
            price: item.charge,
            priceOld: item.charge * 1.2,
            buyCount: item.user_count,
            thumb: item.thumb
          }
        })
        // list = []
        if (page === 1) {
          this.setData({
            courseList: list
          })
        } else {
          this.setData({
            courseList: this.data.courseList.concat(list)
          })
        }
        let status = ''
        if (list.length === 0) {
          status = page === 1 ? 'none' : 'finish'
        }
        return status
      })
    },
    async pulldownRefreshLoad ({detail}) {
      let { success, complete, page } = detail
      try {
        const status = await this.loadCourseList(page)
        success(status)
        complete()
      } catch (err) {
        complete()
      }
      wx.hideLoading()
    },
    onTabsAll () {
      this.showLoading()
      this.setData({
        categoryId: -1
      })
      this.refresh()
    },
    onTabs (e) {
      this.showLoading()
      this.setData({
        categoryId: e.target.dataset.id
      })
      this.refresh()
    },
    showLoading () {
      wx.showLoading({
        title: '加载中',
      })
    },
    refresh () {
      this.selectComponent('#wPulldownRefresh').refresh()
    },
    onSearch (v) {
      this.setData({
        searchKeyword: v.detail
      })
      this.refresh()
    }
  }
})
